import { RouteRecordRaw } from 'vue-router'
// import { Loading } from '@/utils/loading'
import { Session } from '@/utils/storage'

import { TOKEN_KEY } from '@/constants'
import { dynamicRoutes, notFoundAndNoPower } from '@/router/route'
import { router } from '@/router/index'
import { useRouteStore } from '@/stores/modules/routeStore'
import { useUserStore } from '@/stores/modules/userStore'

/**
 * import.meta.glob 用于动态导入模块，可以根据路径动态加载组件，会根据路径不完全匹配
 * @method import.meta.glob
 */
const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}')
export const RouteView = () => import('@/layout/components/main/RouteView.vue')

/**
 * 初始化后端路由
 */
export async function initBackEndControlRoutes() {
    // 界面 loading 动画开始执行
    // if (window.nextLoading === undefined) Loading.start()
    // 无 token 停止执行下一步
    if (!Session.get(TOKEN_KEY)) return false
    // 触发初始化用户信息 pinia
    await useUserStore().setUserInfo()
    // 获取路由菜单数据
    const routes: any = await useRouteStore().getRoutes()
    if (routes.length <= 0) return Promise.resolve(true)
    //处理路由 component 改为动态引入组件，替换 dynamicRoutes 第一个顶级children 的路由
    dynamicRoutes[0].children = await backEndComponent(routes)
    // 添加动态路由
    await setAddRoute()
    //缓存路由，将路由设置到 pinia 中 用于左侧菜单
    await setFilterMenu()
}

/**
 *  后端路由 component 转换
 * @param routes 后端返回的路由表数组
 * @returns 返回处理成函数后的 component
 */
export const backEndComponent = (routes: any) => {
    if (!routes) return
    return routes.map((item: any) => {
        if (item.component) item.component = dynamicImport(item.component as string)
        if (item.children) {
            backEndComponent(item.children)
        }
        return item
    })
}

/**
 * 将后端返回路由中组件路径转化为动态组件引入
 * @param component 路由 组件路径
 */
const dynamicImport = (component: string) => {
    // 目录
    if (component.toString() == 'Layout') {
        return RouteView
    } else {
        const _component = viewsModules[`../views/${component}.vue`]
        return _component ? _component : viewsModules['../views/error/404.vue']
    }
}

/**
 * 添加路由
 */
export const setAddRoute = async () => {
    setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
        router.addRoute(route)
    })
}

/**
 *  处理路由格式及添加扑火所有路由或404 Notfount 路由
 */
export const setFilterRouteEnd = () => {
    const filterRouteEnd: any = dynamicRoutes
    // notFoundAndNoPower 防止 404、401 不在 layout 布局中，不设置的话，404、401 界面将全屏显示
    // 关联问题 No match found for location with path 'xxx'
    filterRouteEnd[0].children = [...filterRouteEnd[0].children, ...notFoundAndNoPower]
    return filterRouteEnd
}

/**
 *  获取动态路由表，缓存到pinia中，用来加载菜单
 */
export const setFilterMenu = async () => {
    useRouteStore().setRouteList(dynamicRoutes[0].children as any)
}
